/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.spark.jwt.util;

import cn.hutool.core.util.StrUtil;
import com.spark.jwt.model.UserInfo;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>jwt token工具类</p>
 * <pre>
 *     jwt的claim里一般包含以下几种数据:
 *         1. iss -- token的发行者
 *         2. sub -- 该JWT所面向的用户
 *         3. aud -- 接收该JWT的一方
 *         4. exp -- token的失效时间
 *         5. nbf -- 在此时间段之前,不会被处理
 *         6. iat -- jwt发布时间
 *         7. jti -- jwt唯一标识,防止重复使用
 * </pre>
 *
 * @author fengshuonan
 * @Date 2017/8/25 10:59
 */
public class JwtTokenUtil {

    private static PrivateKey privateKey = null;
    private static PublicKey publicKey = null;

    static {
        try {
            //这个在Liunx下有问题
            /*publicKey = RsaKeyHelper.getPublicKey(RsaKeyHelper.generatePublicKey(JwtConstants.SECRET));
            privateKey = RsaKeyHelper.getPrivateKey(RsaKeyHelper.generatePrivateKey(JwtConstants.SECRET));*/

            publicKey = RsaKeyHelper.getPublicKey(RsaKeyHelper.toBytes(JwtConstants.publicKey));
            privateKey = RsaKeyHelper.getPrivateKey(RsaKeyHelper.toBytes(JwtConstants.privateKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户名从token中
     */
    public static Long getUserIdFromToken(String token) {
        return Long.parseLong(getClaimFromToken(token).getSubject());
    }

    public static UserInfo getUserInfoFromToken(String token) {
        if (token.startsWith(JwtConstants.AUTH_BEARER)) {
            token = StringUtils.stripStart(token, JwtConstants.AUTH_BEARER).trim();
        }
        Claims body = getClaimFromToken(token);
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Long.parseLong(body.getSubject()));

        userInfo.setName(StrUtil.toString(body.get("name")));
        userInfo.setAvatar(StrUtil.toString(body.get("avatar")));
        return userInfo;
    }

    /**
     * 获取jwt的payload部分
     */
    public static Claims getClaimFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(publicKey)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取jwt发布时间
     */
    public static Date getIssuedAtDateFromToken(String token) {
        return getClaimFromToken(token).getIssuedAt();
    }

    /**
     * 获取jwt失效时间
     */
    public static Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token).getExpiration();
    }

    /**
     * 获取jwt接收者
     */
    public static String getAudienceFromToken(String token) {
        return getClaimFromToken(token).getAudience();
    }

    /**
     * 获取私有的jwt claim
     */
    public static String getPrivateClaimFromToken(String token, String key) {
        return getClaimFromToken(token).get(key).toString();
    }


    /**
     * 解析token是否正确,不正确会报异常<br>
     */
    public static void parseToken(String token) throws JwtException {
        Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();
    }

    /**
     * <pre>
     *  验证token是否失效
     *  true:过期   false:没过期
     * </pre>
     */
    public static Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            return expiration.before(new Date());
        } catch (ExpiredJwtException expiredJwtException) {
            return true;
        }
    }

    /**
     * 生成token(通过用户名和签名时候用的随机数)
     */
    public static String generateToken(UserInfo userInfo) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("name", userInfo.getName());
        claims.put("avatar", userInfo.getAvatar());
        return doGenerateToken(claims, userInfo.getUserId() + "");
    }

    /**
     * 生成token
     */
    private static String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = new Date();
        final Date expirationDate = new Date(createdDate.getTime() + JwtConstants.EXPIRATION * 1000);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }


    public static void main(String[] args) {
        UserInfo userInfo = getUserInfoFromToken("eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxIiwibmFtZSI6IuaZk-W7uiIsImF2YXRhciI6IjEucG5nIiwiZXhwIjoxNTU5Njk3NDI4LCJpYXQiOjE1NTkwOTI2Mjh9.RD47ZM4mD2OTCLELKojmEIRrcTRxvLBGcM3bEsdjNBF0n06DDQolM7UwfnY21qliU0gD23inW8OqAsrFalixtkHGfi4Y4BVhWC25R_ueVRQpP0GX0V2didyXOnd8RE9Xrodw2cCo7nU_xU2fRKqwlcdYBEpMRBL7T03huTYV4mk");
        System.out.println(userInfo.getAvatar());

        userInfo = new UserInfo();
        userInfo.setUserId(1l);
        userInfo.setName("晓建");
        userInfo.setAvatar("abc.jpg");
        String s = generateToken(userInfo);
        System.out.println(s);
        userInfo = getUserInfoFromToken(s);
        System.out.println(userInfo.getName());
    }

}